﻿using InhollandAir.App_Code;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace InhollandAir
{
    public partial class BookedFlights : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                var user = new User();
                if (Application["ActiveUsers"] != null)
                {
                    Dictionary<string, User> activeUsers = (Dictionary<string, User>)Application["ActiveUsers"];
                    var userExists = activeUsers.ContainsKey(Session.SessionID) ? user.Load(Session.SessionID, (Dictionary<string, User>)Application["ActiveUsers"]) : false;
                    if (userExists)
                    {
                        try
                        {
                            user.LoadBookedFlightsFromDb();
                            Logging.WriteActivity("Booked flights loaded from db, UserID: " + user.id);
                        }
                        catch (Exception ex)
                        {
                            //log exception
                            Logging.WriteError(ex.Message + ". UserID: "+ user.id);
                            lbl_BookedFlights.Text = "<p class='alert alert-error'>Can't load booked flights. Please contact the admin.</p>";
                        }

                        if (user.bookedFlights != null)
                        {
                            foreach (KeyValuePair<int, Flight> keyFlight in user.bookedFlights)
                            {
                                lbl_BookedFlights.Text += "<tr>";
                                DateTime dt = DateTime.Parse(keyFlight.Value.departureDate);
                                string convertedDate = dt.ToString("dd-MM-yyyy");
                                lbl_BookedFlights.Text += "<td>" + Server.HtmlEncode(convertedDate) + "</td>";
                                lbl_BookedFlights.Text += "<td>" + Server.HtmlEncode(keyFlight.Value.departureTime) + "</td>";
                                lbl_BookedFlights.Text += "<td>" + Server.HtmlEncode(keyFlight.Value.airportFrom.city) + "</td>";
                                lbl_BookedFlights.Text += "<td>" + Server.HtmlEncode(keyFlight.Value.airportTo.city) + "</td>";
                                lbl_BookedFlights.Text += "<td>" + Server.HtmlEncode(keyFlight.Value.price) + "</td>";
                                lbl_BookedFlights.Text += "<td>" + Server.HtmlEncode(keyFlight.Value.travelTime) + " hr</td>";
                                lbl_BookedFlights.Text += "<td>" + Server.HtmlEncode(keyFlight.Value.flightNr) + "</td>";
                                lbl_BookedFlights.Text += "<td>";
                                if (dt >= DateTime.Now)
                                {
                                    lbl_BookedFlights.Text += "<button class='btn btn-primary' name='remove' type='submit' value='" + keyFlight.Key.ToString() + "'>Cancel this booking</button>";
                                }
                                lbl_BookedFlights.Text += "</td>";
                                lbl_BookedFlights.Text += "</tr>";
                            }
                        }
                    }
                    else
                    {
                        Response.Redirect("/Login.aspx");
                    }
                }
                else
                {
                    //log: application variable doesn't exist
                    Logging.WriteError("Application variable ActiveUsers doesn't exist");
                    Response.Redirect("/Login.aspx");
                }
            }
            else
            {                
                var user = new User();
                if (Application["ActiveUsers"] != null)
                {
                    Dictionary<string, User> activeUsers = (Dictionary<string, User>)Application["ActiveUsers"];
                    var userExists = activeUsers.ContainsKey(Session.SessionID) ? user.Load(Session.SessionID, (Dictionary<string, User>)Application["ActiveUsers"]) : false;
                    if (userExists)
                    {
                        //delete reservation
                        deleteReservation(user);

                        try
                        {                            
                            user.LoadBookedFlightsFromDb();
                            Logging.WriteActivity("Booked flights loaded from db, UserID: " + user.id);
                        }
                        catch (Exception ex)
                        {
                            //log exception
                            Logging.WriteError(ex.Message + ". UserID: " + user.id);
                            lbl_BookedFlights.Text = "<p class='alert alert-error'>Can't load booked flights. Please contact the admin.</p>";
                        }

                        if (user.bookedFlights != null)
                        {
                            foreach (KeyValuePair<int, Flight> keyFlight in user.bookedFlights)
                            {
                                lbl_BookedFlights.Text += "<tr>";
                                DateTime dt = DateTime.Parse(keyFlight.Value.departureDate);
                                string convertedDate = dt.ToString("dd-MM-yyyy");
                                lbl_BookedFlights.Text += "<td>" + Server.HtmlEncode(convertedDate) + "</td>";
                                lbl_BookedFlights.Text += "<td>" + Server.HtmlEncode(keyFlight.Value.departureTime) + "</td>";
                                lbl_BookedFlights.Text += "<td>" + Server.HtmlEncode(keyFlight.Value.airportFrom.city) + "</td>";
                                lbl_BookedFlights.Text += "<td>" + Server.HtmlEncode(keyFlight.Value.airportTo.city) + "</td>";
                                lbl_BookedFlights.Text += "<td>" + Server.HtmlEncode(keyFlight.Value.price) + "</td>";
                                lbl_BookedFlights.Text += "<td>" + Server.HtmlEncode(keyFlight.Value.travelTime) + "</td>";
                                lbl_BookedFlights.Text += "<td>" + Server.HtmlEncode(keyFlight.Value.flightNr) + "</td>";
                                lbl_BookedFlights.Text += "<td>";
                                if (dt >= DateTime.Now)
                                {
                                    lbl_BookedFlights.Text += "<button class='btn btn-primary' name='remove' type='submit' value='" + keyFlight.Key.ToString() + "'>Cancel this booking</button>";
                                }
                                lbl_BookedFlights.Text += "</td>";
                                lbl_BookedFlights.Text += "</tr>";
                            }
                        }
                    }
                    else
                    {
                        Response.Redirect("/Login.aspx");
                    }
                }
                else
                {
                    //log: application variable doesn't exist
                    Logging.WriteError("Application variable ActiveUsers doesn't exist");
                    Response.Redirect("/Login.aspx");
                }
            }
        }

        protected void deleteReservation(User user)
        {
            try
            {
                user.RemoveReservation(int.Parse(Request.Form["remove"]));
                lbl_BookedFlights.Text = "<p class='alert alert-info'>Reservation removed</p>";
                // save/update user in server cache
                Dictionary<string, User> activeUsers = (Dictionary<string, User>)Application["ActiveUsers"];
                List<string> sessionIds = new List<string>();
                foreach (KeyValuePair<string, User> sessionidUser in (Dictionary<string, User>)Application["ActiveUsers"])
                {
                    if (sessionidUser.Value.id == user.id)
                    {
                        //activeUsers[sessionidUser.Key] = user;
                        sessionIds.Add(sessionidUser.Key);
                    }
                }
                foreach (string listItem in sessionIds)
                {
                    activeUsers[listItem] = user;
                }
                Application["ActiveUsers"] = activeUsers;
                Logging.WriteActivity("ReservationID: " + Request.Form["remove"] + " removed with UserID: " + user.id);
            }
            catch (Exception ex)
            {
                //log exception
                Logging.WriteError(ex.Message + ". UserID: " + user.id);
                //
                lbl_BookedFlights.Text = "<p class='alert alert-error'>Failed to remove reservation</p>";
            }                         
        }
    }
}